package cc.linker.steplink.crm.mq.content;

import cc.linker.steplink.crm.merchant.dao.ShopGoodsMapper;
import cc.linker.steplink.crm.merchanth5.service.acs.DynamicService;
import com.alibaba.fastjson.JSON;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;

import java.util.HashMap;
import java.util.Map;

/**
 * @Description: 接收文章商品绑定关系
 * @Author: wuyue
 * @Date: 2019/9/11 16:04
 * @Version: v1.8.3
 */
@Slf4j
@Component
public class ArticleMqReceiver {

    @Autowired
    private ShopGoodsMapper shopGoodsMapper;
    @Autowired
    private DynamicService dynamicService;

    /**
     * @Description: 获取商品和文章的绑定关系
     * @Param: newsId 文章id
     * @Param: goodsIds 商品id，多个逗号拼接
     * @Return: void
     * @Author: wuyue
     * @Date: 2019/9/11 16:05
     * @Version: v1.8.3
     */
    @Async
    public void direct(String msg) {
        try {
            LOGGER.info("从mq接收文章商品绑定关系数据：" + msg);
            Map map = JSON.parseObject(msg, Map.class);
            String newsId = (String) map.get("newsId");
            String goodsIds = (String) map.get("goodsIds");
            if (StringUtils.isEmpty(newsId) || StringUtils.isEmpty(goodsIds)) {
                LOGGER.info("mq信息不正确");
                return;
            }
            // 删除不在goodsIds中但是articleId等于newsId的商品的文章关联
            shopGoodsMapper.deleteGoodsBindArticleByMq(map);
            Map<String, Object> bind = new HashMap<>();
            String[] split = goodsIds.split(",");
            bind.put("goodsId", split);
            bind.put("newsId", newsId);
            // 绑定newsId和goodsIds的关联
            shopGoodsMapper.updateGoodsBindArticleByMq(bind);
        } catch (Exception e) {
            LOGGER.error("mq数据错误");
        }
    }

    /**
     * 获取并记录用户发布文章、下架文章的动态
     */
    @Async
    public void direct2(String msg) {
        try {
            LOGGER.info("从mq接收文章发布下架关系数据：" + msg);
            Map map = JSON.parseObject(msg, Map.class);
            String orgId = (String) map.get("orgNum");
            String adminId = (String) map.get("userId");
            // -1-发布 1-上架 0-下架
            Integer newsState = (Integer) map.get("newsState");
            if (newsState == null) {
                return;
            }
            int type;
            String desc;
            if (newsState == -1) {
                type = 3;
                desc = "发布";
            } else if (newsState == 0) {
                type = 4;
                desc = "下架";
            } else {
                return;
            }
            dynamicService.recording(adminId, orgId, type, desc+map.get("title"));
        } catch (Exception e) {
            LOGGER.error("mq数据错误");
        }
    }
}
